<?php

namespace app\admin\controller\product;

// 引入基类控制器
use app\common\controller\Backend;

class Product extends Backend
{
    protected $TypeModel;
    protected $UnitModel;

    public function __construct()
    {
        parent::__construct();
        // 加载模型
        $this->model = model('Product.Product');
        $this->TypeModel = model('Product.Type');
        $this->UnitModel = model('Product.Unit');

        // 获取商品单位数据组成下拉框需要的数据
        $UnitList = $this->UnitModel->column('id,name');

        // 获取商品分类数据组成下拉框需要的数据
        $TypeList = $this->TypeModel->column('id,name');

        // 注入前置数据
        $this->assign([
            'flagList' => $this->model->getFlagList(),
            'statusList' => $this->model->getStatusList(),
            'unitList' => $UnitList,
            'typeList' => $TypeList
        ]);

        // myPrinf($this->model->getFlagList());exit;
    }
    public function index()
    {
        if ($this->request->isAjax()) {
            // 过滤请求参数中的html标签和取消两边你空白
            $this->request->filter(['strip_tags', 'trim']);
            // 获取查询参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            $total = $this->model
                ->with(['type', 'unit'])
                ->where($where)
                ->count();

            $list = $this->model
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            // var_dump($this->model->getLastSql());
            // exit;

            $result = [
                'rows' => $list,
                'total' => $total,
            ];

            return json($result);
        }

        return $this->view->fetch();
    }
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');
            // 组装数据
            $data = [
                "name"    => $params['name'],
                "price"   => $params['price'],
                "flag"    => $params['flag'],
                "status"  => $params['status'],
                "typeid"  => $params['typeid'],
                "unitid"  => $params['unitid'],
                "thumbs"  => $params['thumbs'],
                "content" => $params['content'],
            ];

            $result = $this->model->validate('common/Product/Product')->save($data);

            if ($result) {
                $this->success();

                exit;
            } else {
                // 拿到所有图片并去空
                $arr = explode(',', $params['thumbs']);
                $arr = array_filter($arr);

                foreach ($arr as $thumb) {
                    $thumb = ltrim($thumb, '/');
                    // 删除
                    @is_file($thumb) && @unlink($thumb);
                }

                $this->error($this->model->getError());

                exit;
            }
        }

        return $this->view->fetch();
    }
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);

        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }

        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');
            // 组装数据
            $data = [
                "id"      => $ids,
                "name"    => $params['name'],
                "price"   => $params['price'],
                "flag"    => $params['flag'],
                "status"  => $params['status'],
                "typeid"  => $params['typeid'],
                "unitid"  => $params['unitid'],
                "thumbs"  => $params['thumbs'],
                "content" => $params['content'],
            ];

            $result = $this->model->validate('common/Product/Product')->isUpdate(true)->save($data);

            if ($result) {
                if ($data['thumbs'] !== $row['thumbs']) {
                    $newArr = array_filter(explode(',', $data['thumbs']));
                    $oldArr = array_filter(explode(',', $row['thumbs']));

                    foreach ($oldArr as $thumb) {
                        // 判断新的图片是否有这张图片
                        if (!in_array($thumb, $newArr)) {
                            $thumb = ltrim($thumb, '/');
                            // 删除
                            @is_file($thumb) && @unlink($thumb);
                        }
                    }
                }

                $this->success();

                exit;
            } else {
                $this->error($this->model->getError());

                exit;
            }
        }

        $this->view->assign("row", $row);

        return $this->view->fetch();
    }
    public function del($ids = null)
    {
        $ids = empty($ids) ? [] : explode(',', $ids);
        $list = $this->model->whereIn('id', $ids)->select();

        foreach ($list as $v) {
            if (!in_array($v['id'], $ids)) {
                $this->error('没有找到商品');
                exit;
            }
        }

        // var_dump($list);
        // exit;

        // 软删除
        $result = $this->model->destroy($ids);

        if ($result) {
            $this->success('删除成功');
            exit;
        } else {
            $this->error($this->model->getError());
            exit;
        }
    }
    // 回收站数据
    public function recyclebin()
    {
        if ($this->request->isAjax()) {
            // 过滤请求参数中的html标签和取消两边你空白
            $this->request->filter(['strip_tags', 'trim']);
            // 获取查询参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            $total = $this->model
                ->onlyTrashed()
                ->with(['type', 'unit'])
                ->where($where)
                ->count();

            $list = $this->model
                ->onlyTrashed()
                ->with(['type', 'unit'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            // var_dump($this->model->getLastSql());
            // exit;

            $result = [
                'rows' => $list,
                'total' => $total,
            ];

            return json($result);
        }

        return $this->view->fetch();
    }
    // 还原
    public function restore($ids = null)
    {
        if ($this->request->isAjax()) {
            $ids = empty($ids) ? [] : explode(',', $ids);

            if (empty($ids)) {
                $this->error(__('No Results were found'));
                exit;
            }

            $list = $this->model->onlyTrashed()->whereIn('id', $ids)->select();

            if (!$list || empty($list)) {
                $this->error(__('No Results were found'));
                exit;
            }

            // 设置删除时间为 null
            $result = $this->model->onlyTrashed()->whereIn('id', $ids)->update(['deletetime' => null]);

            if ($result) {
                $this->success('还原成功');
            } else {
                $this->error('还原失败');
            }
        }
    }
    // 销毁
    public function destroy($ids = null)
    {
        if ($this->request->isAjax()) {
            $ids = empty($ids) ? [] : explode(',', $ids);

            if (!$ids) {
                $this->error(__('No Results were found'));
                exit;
            }

            $list = $this->model->onlyTrashed()->whereIn('id', $ids)->select();

            if (!$list || empty($list)) {
                $this->error(__('No Results were found'));
                exit;
            }

            // 删除数据
            $result = $this->model->onlyTrashed()->whereIn('id', $ids)->delete(true);

            if ($result) {
                foreach ($list as $item) {
                    // 拿到所有图片并去空
                    $arr = explode(',', $item['thumbs']);
                    $arr = array_filter($arr);

                    foreach ($arr as $thumb) {
                        $thumb = ltrim($thumb, '/');
                        // 删除
                        @is_file($thumb) && @unlink($thumb);
                    }
                }

                $this->success('销毁成功');
            } else {
                $this->error('销毁失败');
            }
        }
    }
}
